package com.peoit.honeycomb.application.impl;

import java.util.List;
import java.util.UUID;

import javax.transaction.Transactional;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.peoit.honeycomb.application.SmsTemplateApplication;
import com.peoit.honeycomb.domain.SmsTemplate;
import com.peoit.honeycomb.domain.repository.HibernateEntityRepository;

@Service
public class SmsTemplateApplicationImpl extends HibernateEntityRepository implements SmsTemplateApplication {

	@Override
	public List<SmsTemplate> getAllSmsTemplate() {
		String hql = " from SmsTemplate where 1=1 order by createTime";
		return this.queryByFullJPQL(hql, null);
	}

	@Override
	@Transactional
	public boolean activeSmsTemplate(String type, String id) {
		String hql = "update SmsTemplate set status=? where id = ?";
		Object[] params = { true, id };
		updateByFullJPQL(hql, params);
		String hql2 = "update SmsTemplate set status=? where type= ? and id <> ?";
		Object[] params2 = { false, type, id };
		updateByFullJPQL(hql2, params2);
		return true;
	}

	@Override
	@Transactional
	public boolean saveSmsTemplate(SmsTemplate st) {
		if (StringUtils.isEmpty(st.getId())) {
			st.setId(UUID.randomUUID().toString());
			if (st.isStatus()) {
				String hql = "update SmsTemplate set status=? where type=?";
				Object[] params = { false, st.getType() };
				updateByFullJPQL(hql, params);
			}
			create(st);
		} else {
			SmsTemplate old = find(SmsTemplate.class, st.getId());
			old.setAccount(st.getAccount());
			old.setPswd(st.getPswd());
			old.setExtno(st.getExtno());
			old.setMsg(st.getMsg());
			old.setType(st.getType());
			old.setStatus(st.isStatus());
			old.setNeedstatus(st.isNeedstatus());
			old.setProduct(st.getProduct());
			old.setLength(st.getLength());
			old.setFailureTime(st.getFailureTime());
			if (st.isStatus()) {
				String hql = "update SmsTemplate set status=? where type=? and id <> ?";
				Object[] params = { false, st.getType(), st.getId() };
				updateByFullJPQL(hql, params);
			}
		}
		return true;
	}

}
